import React, { useState, useCallback, useEffect } from 'react'
import { useHistory, useLocation } from 'react-router-dom'
import { useSelector, useDispatch } from 'react-redux'

import { actionCreater } from '@/views/home/ui/cookbook'

import {
  NavBar,
  Icon,
  ListView
} from 'antd-mobile'

import {
  ListContainer,
  ListWrap,
  SubTitle
} from './StyledList'

function MyBody(props) {
  return (
    <div className="am-list-body my-body">
      {props.children}
    </div>
  );
}

const pageSize = 10
let pageNo = 1

const List = (props) => {
  const list = useSelector(state => state.getIn(['home', 'list']))
  const ds = new ListView.DataSource({
    rowHasChanged: (row1, row2) => row1 !== row2
  })

  let [dataSource, setDataSource] = useState(ds)
  let [isLoading, setIsLoading] = useState(true)
  let [hasMore, setHasMore] = useState(true)
  let [height, setHeight] = useState(document.documentElement.clientHeight)

  const { goBack, push } = useHistory()
  const { state } = useLocation()
  const dispatch = useDispatch()

  const handleLeftClick = useCallback(
    () => {
      goBack()
    },
    [goBack],
  )

  const handleGotoDetail = useCallback(
    (id) => {
      return () => {
        push({ pathname: '/detail', state: { id } })
      }
    },
    [push]
  )

  const onEndReached = useCallback(
    () => {
      pageNo++
      if (pageNo * pageSize > list.length) {
        setHasMore(false)
      }
      if (isLoading && !hasMore) {
        return;
      }
      setIsLoading(true)
      setTimeout(() => {
        let ds = list.slice(0, pageNo * pageSize)
        setDataSource((dataSource) => dataSource.cloneWithRows(ds))
        setIsLoading(false)
      }, 1000)
    },
    [isLoading, hasMore, list]
  )

  useEffect(() => {
    if (list.length === 0) {
      const { loadDataForSaga } = actionCreater
      dispatch(loadDataForSaga())
    }
  }, [dispatch, list])

  useEffect(() => {
    let ls = list.slice(0, pageSize)
    setDataSource((dataSource) => dataSource.cloneWithRows(ls))
  }, [list])

  const row = (item, sectionID, rowID) => {
    return (
      <ListWrap
        width="0 0 1px 0"
        key={item.id + rowID}
        onClick={handleGotoDetail(item.id)}
        >
        <div>
          <img src={item.img} width="115" height="75" alt=""/>
        </div>
        <div>
          <h1>{item.name}</h1>
          <SubTitle>{item.burdens}</SubTitle>
          <h3>{item.all_click}浏览 {item.favorites}收藏</h3>
        </div>
      </ListWrap>
    )
  }

  return (
    <ListContainer>
      <NavBar
        mode="dark"
        icon={<Icon type="left" />}
        onLeftClick={handleLeftClick}
        style={{backgroundColor: '#ee742f' }}
      >
        {state.title}
      </NavBar>
      <ul>
        {
          <ListView
            dataSource={dataSource}
            renderBodyComponent={() => <MyBody />}
            renderRow={row}
            style={{
              height,
              overflow: 'auto',
            }}
            pageSize={4}
            scrollRenderAheadDistance={500}
            onEndReached={onEndReached}
            onEndReachedThreshold={10}
          />
        }
      </ul>
    </ListContainer>
  )
}

export default List
